import { defineComponent, ref, getCurrentInstance, computed } from "vue"
import { inject } from "vue"

import HeaderCheckboxContent from "./header-checkbox-content"
import HeaderFilterContent from "./header-filter-content"
import HeaderFilterCustomContent from "./header-filter-custom-content"
import { getFixedTotalWidthByColumnKey, getColKeysByRangeColKeys, getColKeysByHeaderColumn } from "../util"
import { COMPS_NAME, COLUMN_TYPES, EMIT_EVENTS } from "../util/constant"
import VeIcon from "amtf/components/icon"

import { ICON_NAMES } from "amtf/constants"
import { useEmitter } from "amtf/hooks"

import { use样式 } from "amtf/hooks"
import { isEmptyValue, getValByUnit, 拼组件名, isFunction, isBoolean, getRandomId } from "amtf/utils"
const 主名 = "table-header-th"
const 组件名 = 拼组件名(主名)

export default defineComponent({
    name: COMPS_NAME.VE_TABLE_THADER_Th,
    props: {
        groupColumn: {
            type: Array,
            required: true,
        },
        groupColumnItem: {
            type: Object,
            required: true,
        },
        colgroups: {
            type: Array,
            required: true,
        },
        headerRows: {
            type: Array,
            default: () => [],
        },
        fixedHeader: {
            type: Boolean,
        },
        isGroupHeader: {
            type: Boolean,
            required: true,
        },
        rowIndex: {
            type: Number,
            required: true,
        },
        cellSelectionData: {
            type: Object,
            default: () => null,
        },
        // cell selection range data
        cellSelectionRangeData: {
            type: Object,
            default: () => null,
        },
        headerIndicatorColKeys: {
            type: Object,
            default: () => null,
        },
        // checkbox option
        checkboxOption: {
            type: Object,
            default: () => null,
        },
        // sort option
        sortOption: {
            type: Object,
            default: () => null,
        },
        // sort columns
        sortColumns: {
            type: Object,
            default: () => null,
        },
        // cell style option
        cellStyleOption: {
            type: Object,
            default: () => null,
        },
        // event custom option
        eventCustomOption: {
            type: Object,
            default: () => null,
        },
    },
    setup(props) {
        const instance = getCurrentInstance()
        const { 拼样式名_table直属 } = use样式(主名)
        const { dispatch } = useEmitter(inject("表格id"))
        const { dispatch: dispatch表头 } = useEmitter(inject("表头id"))

        const isLastLeftFixedColumn = computed(() => {
            let result = false
            const { groupColumn, groupColumnItem: column } = props
            const { fixed, _keys } = column

            if (fixed === "left") {
                const leftFixedColumns = groupColumn.filter(x => x.fixed === "left")
                const index = leftFixedColumns.findIndex(x => x._keys === _keys)

                if (index === leftFixedColumns.length - 1) {
                    result = true
                }
            }
            return result
        })

        const isfirstRightFixedColumn = computed(() => {
            let result = false
            const { groupColumn, groupColumnItem: column } = props
            const { fixed, _keys } = column

            if (fixed === "right") {
                const leftFixedColumns = groupColumn.filter(x => x.fixed === "right")

                if (leftFixedColumns[0]._keys === _keys) {
                    result = true
                }
            }
            return result
        })

        const isLastCloumn = computed(() => {
            let result = false
            const { colgroups, groupColumnItem: column } = props
            const lastColumnKey = colgroups[colgroups.length - 1].key
            const keys = column._keys.split("|")

            if (keys.length) {
                if (keys.length === 1) {
                    if (keys[0] === lastColumnKey) {
                        result = true
                    }
                } else if (keys[keys.length - 2] === lastColumnKey) {
                    result = true
                }
            }
            return result
        })

        const isSortableCloumn = computed(() => {
            let result = false
            const { sortColumns, groupColumnItem } = props
            const currentField = groupColumnItem.field

            if (Object.keys(sortColumns).includes(currentField)) {
                result = true
            }
            return result
        })

        const getTheadThClass = ({ fixed }) => {
            let result = {
                [拼样式名_table直属("header-th")]: true,
                [拼样式名_table直属("fixed-left")]: fixed === "left",
                [拼样式名_table直属("fixed-right")]: fixed === "right",
                [拼样式名_table直属("last-left-fixed-column")]: isLastLeftFixedColumn.value,
                [拼样式名_table直属("first-right-fixed-column")]: isfirstRightFixedColumn.value,
                [拼样式名_table直属("last-column")]: isLastCloumn.value,
                [拼样式名_table直属("sortable-column")]: isSortableCloumn.value,
            }

            const {
                cellStyleOption,
                rowIndex,
                groupColumnItem: column,
                cellSelectionRangeData,
                colgroups,
                isGroupHeader,
                headerIndicatorColKeys,
            } = props

            if (cellSelectionRangeData) {
                const { leftColKey, rightColKey } = cellSelectionRangeData
                const { startColKeyIndex } = headerIndicatorColKeys
                const isIndicatorActive = startColKeyIndex > -1

                if (!isEmptyValue(leftColKey)) {
                    let indicatorColKeys = []
                    if (leftColKey === rightColKey) {
                        indicatorColKeys = [leftColKey]
                    } else {
                        indicatorColKeys =
                            getColKeysByRangeColKeys({
                                colKey1: leftColKey,
                                colKey2: rightColKey,
                                colgroups,
                            }) ?? []
                    }

                    let showIndicator = false
                    if (!isGroupHeader) {
                        if (indicatorColKeys.indexOf(column["key"]) > -1) {
                            showIndicator = true
                        }
                    } else {
                        const colKeys = getColKeysByHeaderColumn({
                            headerColumnItem: column,
                        })
                        showIndicator = colKeys.every(colKey => {
                            return indicatorColKeys.indexOf(colKey) > -1
                        })
                    }
                    if (showIndicator) {
                        if (isIndicatorActive) {
                            result[拼样式名_table直属("cell-indicator-active")] = true
                        } else {
                            result[拼样式名_table直属("cell-indicator")] = true
                        }
                    }
                }
            }

            if (cellStyleOption && typeof cellStyleOption.headerCellClass === "function") {
                const customClass = cellStyleOption.headerCellClass({
                    column,
                    rowIndex,
                })
                if (customClass) {
                    result[customClass] = true
                }
            }

            return result
        }

        const getTheadThStyle = ({ _keys, align, fixed }, rowIndex) => {
            let result = {}
            const colgroups = props.colgroups
            const headerRows = props.headerRows

            // text align
            result["text-align"] = align || "center"

            // fixed left total width or right total width
            if (fixed) {
                let key = ""
                let totalWidth = 0
                const keys = _keys.split("|")
                if (fixed === "left") {
                    key = keys[0]
                } else if (fixed === "right") {
                    key = keys.length === 1 ? keys[0] : keys[keys.length - 2]
                }

                if (key) {
                    // column index
                    const columnIndex = colgroups.findIndex(x => x.key === key)
                    if (
                        (fixed === "left" && columnIndex > 0) ||
                        (fixed === "right" && columnIndex < colgroups.length - 1)
                    ) {
                        totalWidth = getFixedTotalWidthByColumnKey({
                            colgroups,
                            colKey: key,
                            fixed,
                        })

                        totalWidth = getValByUnit(totalWidth)
                    }
                }
                result["left"] = fixed === "left" ? totalWidth : ""
                result["right"] = fixed === "right" ? totalWidth : ""
            }

            // header row th fixed top
            if (props.fixedHeader) {
                let rowHeight = 0
                if (rowIndex > 0) {
                    rowHeight = headerRows.reduce((total, currentVal, index) => {
                        return index < rowIndex ? currentVal.rowHeight + total : total
                    }, 0)
                }
                rowHeight = getValByUnit(rowHeight)

                result["top"] = rowHeight
            }

            return result
        }

        const getCheckboxContent = () => {
            let result = null
            const { checkboxOption } = props

            if (props.groupColumnItem.type === COLUMN_TYPES.CHECKBOX) {
                if (!checkboxOption.hideSelectAll) {
                    // checkbox content props
                    const checkboxProps = {
                        props: {
                            column: props.groupColumnItem,
                            checkboxOption: props.checkboxOption,
                        },
                    }

                    result = <HeaderCheckboxContent {...checkboxProps} />
                }
            }
            return result
        }

        const sortChange = () => {
            let sortResult = ""
            const { sortColumns, groupColumnItem, sortOption } = props
            const { sortAlways } = sortOption

            const currentField = groupColumnItem.field
            const sortBy = sortColumns[currentField]

            if (sortAlways) {
                sortResult = sortBy === "asc" ? "desc" : "asc"
            } else {
                sortResult = sortBy === "asc" ? "desc" : sortBy === "desc" ? "" : "asc"
            }

            dispatch表头(EMIT_EVENTS.SORT_CHANGE, {
                currentField,
                sortResult,
            })
        }

        const getSortContent = () => {
            let result = null
            const { sortColumns, groupColumnItem } = props
            const currentField = groupColumnItem.field

            if (Object.keys(sortColumns).includes(currentField)) {
                const sortBy = sortColumns[currentField]

                const propsData = {
                    class: 拼样式名_table直属("sort"),
                }

                result = (
                    <span {...propsData}>
                        <VeIcon
                            class={[
                                拼样式名_table直属("sort-icon"),
                                拼样式名_table直属("sort-icon-top"),
                                sortBy === "asc" ? "active" : "",
                            ]}
                            name={ICON_NAMES.SORT_TOP_ARROW}
                        />
                        <VeIcon
                            class={[
                                拼样式名_table直属("sort-icon"),
                                拼样式名_table直属("sort-icon-bottom"),
                                sortBy === "desc" ? "active" : "",
                            ]}
                            name={ICON_NAMES.SORT_BOTTOM_ARROW}
                        />
                    </span>
                )
            }

            return result
        }

        const getFilterContent = () => {
            // console.log(`getFilterContent ing👇`)
            let result = null
            const { groupColumnItem } = props
            if (groupColumnItem.filter) {
                const filterProps = {
                    column: props.groupColumnItem,
                }
                result = <HeaderFilterContent {...filterProps} />
            }
            return result
        }
        // getFilterContent()

        const getFilterCustomContent = () => {
            let result = null
            const { groupColumnItem } = props

            if (groupColumnItem.filterCustom) {
                // filter content props
                const filterProps = {
                    column: props.groupColumnItem,
                }
                result = <HeaderFilterCustomContent {...filterProps} />
            }
            return result
        }

        const cellClick = (e, fn) => {
            fn && fn(e)
            const { groupColumnItem } = props
            dispatch(EMIT_EVENTS.HEADER_CELL_CLICK, {
                event: e,
                column: groupColumnItem,
            })

            if (isSortableCloumn.value && e.target instanceof HTMLTableCellElement) {
                sortChange()
            }
        }

        const cellDblclick = (e, fn) => {
            fn && fn(e)
        }

        const cellContextmenu = (e, fn) => {
            fn && fn(e)
            const { groupColumnItem } = props
            dispatch(EMIT_EVENTS.HEADER_CELL_CONTEXTMENU, {
                event: e,
                column: groupColumnItem,
            })
        }

        const cellMouseenter = (e, fn) => {
            // console.log(`cellMouseenter ing👇`)
            // console.log(`fn 👉`, fn)
            fn && fn(e)
        }

        const cellMouseleave = (e, fn) => {
            fn && fn(e)
            const { groupColumnItem } = props
            dispatch(EMIT_EVENTS.HEADER_CELL_MOUSELEAVE, {
                event: e,
                column: groupColumnItem,
            })
        }

        const cellMousemove = (e, fn) => {
            // console.log(`cellMousemove ing👇`)
            fn && fn(e)
            const { groupColumnItem } = props
            dispatch(EMIT_EVENTS.HEADER_CELL_MOUSEMOVE, {
                event: e,
                column: groupColumnItem,
            })
        }

        const cellMouseover = (e, fn) => {
            fn && fn(e)
            const { groupColumnItem } = props
            dispatch(EMIT_EVENTS.HEADER_CELL_MOUSEOVER, {
                event: e,
                column: groupColumnItem,
            })
        }

        const cellMousedown = (e, fn) => {
            fn && fn(e)
            const { groupColumnItem } = props
            dispatch(EMIT_EVENTS.HEADER_CELL_MOUSEDOWN, {
                event: e,
                column: groupColumnItem,
            })
        }

        const cellMouseup = (e, fn) => {
            fn && fn(e)
        }

        return () => {
            const { groupColumnItem, rowIndex, eventCustomOption } = props
            let content
            if (typeof groupColumnItem.renderHeaderCell === "function") {
                const { ...column } = groupColumnItem
                const renderResult = groupColumnItem.renderHeaderCell(
                    {
                        column,
                    },
                    instance.render
                )
                content = renderResult
            } else {
                content = groupColumnItem.title
            }

            // custom on cell event
            let customEvents = {}
            if (eventCustomOption) {
                console.log(`eventCustomOption 👉`, eventCustomOption)
                const { headerCellEvents } = eventCustomOption
                customEvents = headerCellEvents ? headerCellEvents({ column: groupColumnItem, rowIndex }) : {}
            }

            const { click, dblclick, contextmenu, mouseenter, mouseleave, mousemove, mouseover, mousedown, mouseup } =
                customEvents

            const events = {
                onClick: e => cellClick(e, click),
                onDblclick: e => cellDblclick(e, dblclick),
                onContextmenu: e => cellContextmenu(e, contextmenu),
                onMouseenter: e => cellMouseenter(e, mouseenter),
                onMouseleave: e => cellMouseleave(e, mouseleave),
                onMousemove: e => cellMousemove(e, mousemove),
                onMouseover: e => cellMouseover(e, mouseover),
                onMousedown: e => cellMousedown(e, mousedown),
                onMouseup: e => cellMouseup(e, mouseup),
            }

            const thProps = {
                style: getTheadThStyle(groupColumnItem, rowIndex),
                class: getTheadThClass(groupColumnItem),
                rowspan: groupColumnItem._rowspan,
                colspan: groupColumnItem._colspan,
                ...events,
            }

            return (
                <th {...thProps}>
                    {getCheckboxContent()}
                    {content}
                    {getSortContent()}
                    {getFilterContent()}
                    {getFilterCustomContent()}
                </th>
            )
        }
    },
})
